
//
//  BPPicWeiBoControl.swift
//  BPWeiBo
//
//  Created by 扒皮大叔 on 16/4/16.
//  Copyright © 2016年 apple. All rights reserved.
import UIKit
import HMImagePicker
import SVProgressHUD
import SnapKit
private let reuseIdentifier = "itemCell"
//设置cell之间的间距和每一行的cell的个数
private let cellMargin:CGFloat = 3
private let cellCount:CGFloat = 4
//设置显示的最大的cell的个数
private let maxCellCount = 9

class BPPicWeiBoControl: UICollectionViewController {
    
    //设置cell的属性
    //private var picCell:BPPicCollectionCell = BPPicCollectionCell()    
    private var indexPath:NSIndexPath = NSIndexPath()
    
    private var selectedAsset: [PHAsset]?
    
    var selectedimg:[UIImage] = [UIImage](){
        didSet{
            if self.parentViewController != nil {
               let appearControl = self.parentViewController as! BPAppearWeiboControl
                if selectedimg.count > 0 {
                    appearControl.navigationItem.rightBarButtonItem?.enabled = true
                }else {
                    appearControl.navigationItem.rightBarButtonItem?.enabled = false
                }
            }
            
        }
    }
    //创建选中cell的ID
    //var selectedCellID = "selectedCell"
    
    //MARK:在init方法 中设置布局
    init() {
        
        let layout = UICollectionViewFlowLayout()
        layout.itemSize = CGSize(width: 80, height: 80)
        let itemW = (ScreenWidth - ((cellCount + 1)*cellMargin)) / cellCount
        let itemH = itemW
        layout.itemSize = CGSize(width: itemW, height: itemH)
        layout.minimumInteritemSpacing = cellMargin
        layout.minimumLineSpacing = cellMargin
        //设置cell的内边距
        layout.sectionInset = UIEdgeInsets(top: cellMargin, left: cellMargin, bottom: cellMargin, right: cellMargin)
        
        super.init(collectionViewLayout: layout)
        collectionView?.bounces = false
        collectionView?.showsHorizontalScrollIndicator = false
        collectionView?.showsVerticalScrollIndicator = false
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        //如果要设置tableviewController或者collectionViewController的背景色,需要设置他们的tableview或者collectionView
        collectionView?.backgroundColor = UIColor.clearColor()

        // Register cell classes.注册cell
        self.collectionView!.registerClass(BPPicCollectionCell.self, forCellWithReuseIdentifier: reuseIdentifier)

    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

}


//MARK:----------------------------------------------------
//MARK:数据源方法
extension BPPicWeiBoControl{
    // MARK: UICollectionViewDataSource.数据源方法
    
    override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }
    
    
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of items
        let detla = selectedimg.count >= maxCellCount ? 0 : 1
        return selectedimg.count + detla
    }
    
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! BPPicCollectionCell
        self.indexPath = indexPath
        //设置cell的具体的数据
        cell.backgroundColor = UIColor.whiteColor()
        
        cell.selectedDeleget = self
        
        
        if indexPath.item == selectedimg.count {
            //程序走到这个地方  如果去数组根据索引取值 就会造成数组索引越界
            cell.imgView.image = UIImage(named: "compose_pic_add_highlighted")
            cell.removebtn.hidden = true
        } else {
      
            cell.imgView.image = selectedimg[indexPath.item]
            cell.removebtn.hidden = false

        }
        return cell
    }
 
}


//MARK:----------------------------------------------------
//MARK:代理方法
extension BPPicWeiBoControl {

    
    //当选中某一个cell的时候,会调用这个方法
    override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
//        //1.获取系统的相册
//        let picker = UIImagePickerController()
//        //设置始终有权限进入
//        picker.allowsEditing = true
//        //设置它的代理
//        picker.delegate = self
        let cell = collectionView.cellForItemAtIndexPath(indexPath) as! BPPicCollectionCell
        
        if cell.removebtn.hidden == false {
            SVProgressHUD.showErrorWithStatus("已经选过图片了哦")
            return
        }
        
        //MARK:使用第三方框架
        let hmPicker = HMImagePickerController(selectedAssets: selectedAsset)
        //设置代理
        hmPicker.pickerDelegate = self
        hmPicker.targetSize = CGSize(width: 600, height: 600)
        hmPicker.maxPickerCount = maxCellCount
        
        
        //collectionView.reloadData()
        //跳转到源控制器
        presentViewController(hmPicker, animated: true, completion: nil)
        
    }
    
}


//MARK:----------------------------------------------------
//MARK:系统相册的代理方法
//extension BPPicWeiBoControl:UIImagePickerControllerDelegate,UINavigationControllerDelegate {
//    
//    //当选择图片完成的时候
//    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
//        //获取图片
//        selectedimg.append(image)
//        
//        dismissViewControllerAnimated(true, completion: nil)
//    }
//    
//    func imagePickerControllerDidCancel(picker: UIImagePickerController) {
//        
//    }
//
//}

//MARK:----------------------------------------------------
//MARK:第三方库的代理方法
extension BPPicWeiBoControl:HMImagePickerControllerDelegate,PictureSelectorCellDelegate {
    
    func imagePickerController(picker: HMImagePickerController, didFinishSelectedImages images: [UIImage], selectedAssets: [PHAsset]?) {
        self.selectedimg = images
        self.selectedAsset = selectedAssets
        self.collectionView?.reloadData()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    //MARK:实现自定义cell的代理方法
    func userWillDeletePicture(cell: BPPicCollectionCell) {
        //1.获取用户点击的是哪一个cell
        //通过协议方法的参数获取用户点击的cell
        //2.获取cell对应的indexPath
        if let indexPath = collectionView?.indexPathForCell(cell) {
            
            cell.removebtn.hidden = true
            //3.在数组中移除对应 indexPath.item 对应的元素
            selectedimg.removeAtIndex(indexPath.item)
            //collect我靠正的hennhsAtIndexPaths([indexPath])
            //删除上一次选择图片的数据源
            self.selectedAsset?.removeAtIndex(indexPath.item)
            if selectedimg.count == 0 {
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.view.snp_updateConstraints(closure: { (make) -> Void in
                        make.height.equalTo(0)
                    })
                })

            }
            //刷新数据
            collectionView?.reloadData()
        }
    }
}

//MARK:定义协议
@objc protocol PictureSelectorCellDelegate: NSObjectProtocol {
    //d定义协议方法
    //optional func userWillChosePicture()
    
    //用户将要删除图片
    optional func userWillDeletePicture(cell: BPPicCollectionCell)
}


//MARK:----------------------------------------------------
//MARK:自定义cell

class BPPicCollectionCell: UICollectionViewCell {
    
    //定义一个代理对象是弱引用
    weak var selectedDeleget :PictureSelectorCellDelegate?
    
    private lazy var imgView:UIImageView = UIImageView(image: UIImage(named: "compose_pic_add"))
    private lazy var removebtn:UIButton = {
        let btn = UIButton()
        btn.setBackgroundImage(UIImage(named: "compose_photo_close"), forState: .Normal)
        btn.sizeToFit()
        return btn
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setCellUpUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setCellUpUI() {
        
        addSubview(imgView)
        addSubview(removebtn)
        //设置约束
        self.imgView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(self.snp_edges)
        }
        self.removebtn.snp_makeConstraints { (make) -> Void in
            make.top.right.equalTo(self)
        }
        //设置填充模式
        self.imgView.contentMode = .ScaleAspectFill
        self.imgView.clipsToBounds = true
        self.imgView.userInteractionEnabled = false
        //设置按钮隐藏
        removebtn.hidden = true
        removebtn.addTarget(self, action: "removeCell", forControlEvents: .TouchUpInside)
    }
    
    @objc private func removeCell() {
        selectedDeleget?.userWillDeletePicture!(self)
    }
}

